package com.example.jpa.crud.model;

import com.example.jpa.crud.util.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

public abstract class ResourceModelSupport implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(ResourceModelSupport.class);

    public abstract ResourceModel getResourceModelByName(String name);

    public abstract JsonViewTemplate getResponseTemplate();

    protected abstract void registerJsonViewTemplate(String packageName);

    protected abstract void registerResourceModel(String packageName);

    @Override
    public void run(ApplicationArguments args) {
        final Class<?> mainApplicationClass = deduceMainApplicationClass();
        if (mainApplicationClass == null) {
            log.error("can't find the main application class!");
            return;
        }
        final String packageName = ClassUtils.getPackageName(mainApplicationClass.getName());
        registerResourceModel(packageName);
        registerJsonViewTemplate(packageName);
    }

    private Class<?> deduceMainApplicationClass() {
        try {
            StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                if ("main".equals(stackTraceElement.getMethodName())) {
                    return Class.forName(stackTraceElement.getClassName());
                }
            }
        } catch (ClassNotFoundException ignore) {
        }
        return null;
    }

}
